//
//  OMHomeAddressSelectView.m
//  OMENGO_NEW
//
//  Created by 梁尚嘉 on 2017/4/21.
//  Copyright © 2017年 Kamfat. All rights reserved.
//

#import "OMHomeAddressSelectView.h"
#import "OMHomeAddressSelectTableCell.h"
#import "OMOriginalAddress.h"
#define kTableMinHeight SM_SIZE(80)
#define kAddressCellHeight [OMHomeAddressSelectTableCell cellHeight]
#define kTableMaxHeight (kAddressCellHeight*7.3)
#define kAddButtonHeight SM_SIZE(10)
@interface OMHomeAddressSelectView () <UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *containView;
@property (nonatomic, strong) UIView *backgroundView;
@property (nonatomic, strong) UIButton *addressAddButton;
@property (nonatomic, strong) UIView *requestView;
@property (nonatomic, strong) UIActivityIndicatorView *activityView;
@property (nonatomic, strong) UIButton *errorButton;
@property (nonatomic, strong) OMOriginalAddress *address;


@property (nonatomic, assign, getter=isAnimating) BOOL animating;

@property (nonatomic, strong) NSArray <OMOriginalAddress *>*items;
@end


@implementation OMHomeAddressSelectView

- (instancetype)init
{
    self = [super init];
    [self configure];
    return self;
}

- (void)configure
{
    _address = KTSystemStorageSingleton.originalAddress;

    _backgroundView = [UIView new];
    _backgroundView.backgroundColor = [SM_blackColor colorWithAlphaComponent:.6];
    [self addSubview:_backgroundView];
    [_backgroundView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(@0);
    }];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]init];
    @weakify(self);
    [[tap rac_gestureSignal] subscribeNext:^(id x) {
        @strongify(self);
        [self dismiss];
    }];
    _backgroundView.userInteractionEnabled = true;
    [_backgroundView addGestureRecognizer:tap];


    _containView = [UIView new];
    [self addSubview:_containView];
    [_containView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(SM_SIZE(20)));
        make.top.equalTo(@0);
        make.right.equalTo(@(SM_SIZE(-20)));
    }];

    _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorColor = SM_naviShadowColor;
    [_containView addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(@0);
        make.height.equalTo(@(kTableMinHeight));
    }];

//    UIView *separatorLine = [UIView new];
//    separatorLine.backgroundColor = SM_naviShadowColor;
//    [_containView addSubview:separatorLine];
//    [separatorLine mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.right.equalTo(@0);
//        make.height.equalTo(@.5f);
//        make.top.equalTo(_tableView.mas_bottom).offset(SM_SIZE(0));
//    }];

    UIView *buttonContentView = [UIView new];
    buttonContentView.backgroundColor = SM_whiteColor;
    [self.containView insertSubview:buttonContentView atIndex:0];
    buttonContentView.layer.cornerRadius = SM_SIZE(7);
    buttonContentView.clipsToBounds = true;
    [buttonContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(@0);
        make.top.equalTo(_tableView.mas_bottom).offset(-SM_SIZE(7));
        make.height.equalTo(@(kAddButtonHeight+SM_SIZE(7)));
        make.bottom.equalTo(@0);
    }];

//    _addressAddButton = [[UIButton alloc]init];
//    _addressAddButton.backgroundColor = HEXCOLOR(@"#F8F8F9");
//    [_addressAddButton setTitle:@"新增地址" forState:UIControlStateNormal];
//    [_addressAddButton setTitleColor:HEXCOLOR(@"#FFA100") forState:UIControlStateNormal];
//    [_addressAddButton.titleLabel setFont:SM_CFont(35)];
//    [buttonContentView addSubview:_addressAddButton];
//    [_addressAddButton mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.right.bottom.equalTo(@(SM_SIZE(0)));
//        make.top.equalTo(@(SM_SIZE(7)));
//    }];
//    [[_addressAddButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
//        NaviPush(@"OMDeliveryAddressModifyViewController", @{@"isModifying":@(NO)});
//    }];

    _requestView = [UIView new];
    _requestView.frame = CGRectMake(0, 0, SM_SCREEN_WIDTH, kTableMinHeight);
    _activityView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    _activityView.hidesWhenStopped = true;
    [_requestView addSubview:_activityView];
    [_activityView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(SM_SIZE(50)));
        make.centerY.equalTo(_requestView.mas_centerY);
        make.size.mas_equalTo(_activityView.size);
    }];
    _errorButton = [UIButton new];
    [_errorButton setTitle:@"获取地址失败，点击重试" forState:UIControlStateNormal];
    [_requestView addSubview:_errorButton];
    [_errorButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_requestView.mas_centerY);
        make.centerX.equalTo(_requestView.mas_centerX);
    }];
    _errorButton.hidden = true;
    [[_errorButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        @strongify(self);
        [self getProject];
    }];

}

- (void)getProject
{
    self.animating = true;
    [KTHttpUtils GET:@"index/project.jhtml"
          completion:^(id responseObject,
                       BOOL isSuccess,
                       NSString *message)
     {
         if (isSuccess) {
             dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                 self.animating = false;
                 self.items = [OMOriginalAddress mj_objectArrayWithKeyValuesArray:responseObject[OMDataKey]];
                 [self.tableView reloadData];
             });
         }else {
             [self showWithError];
         }
     }];
}

- (void)showWithError
{
    self.errorButton.hidden = false;
}


- (void)setAnimating:(BOOL)animating
{
    _animating = animating;
    [self.tableView beginUpdates];
    if (animating) {
        [self.activityView startAnimating];
        self.tableView.tableHeaderView = self.requestView;
        self.errorButton.hidden = true;
    }else {
        [self.activityView stopAnimating];
        self.tableView.tableHeaderView = nil;
    }
    [self.tableView endUpdates];
}



- (void)setItems:(NSArray *)items
{
    _items = items;
    [self.tableView reloadData];
    CGFloat targetHeight = MIN(_items.count*kAddressCellHeight,kTableMaxHeight);
    [UIView animateWithDuration:0.2 animations:^{
        [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo(@(targetHeight));
        }];
        [self.tableView.superview.superview layoutIfNeeded];
    } completion:^(BOOL finished) {

    }];
}

- (void)showInView:(UIView *)view
{
    [view addSubview:self];
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position.y"];
    animation.fromValue = @(-(kAddButtonHeight+kTableMinHeight));
    animation.toValue = @((kAddButtonHeight+kTableMinHeight)/2);
    animation.duration = .2f;
    [self.containView.layer addAnimation:animation forKey:nil];

    [self getProject];
}

- (void)dismiss
{
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position.y"];
    animation.fromValue = @(self.containView.centerY);
    animation.toValue = @(-self.containView.centerY);
    [self.containView.layer addAnimation:animation forKey:nil];
    animation.duration = .2f;
    [UIView animateWithDuration:0.2 animations:^{
        _backgroundView.alpha = 0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
        if (self.delegate && [self.delegate respondsToSelector:@selector(didDismiss)]) {
            [self.delegate didDismiss];
        }
    }];
}

#pragma mark - tableView delegate && datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{   OMHomeAddressSelectTableCell *cell = [OMHomeAddressSelectTableCell tableViewCellWithTableView:tableView];
    [cell configureCellWithObj:self.items[indexPath.row]];
    cell.om_selected = [self.items[indexPath.row].id isEqualToString:self.address.id];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kAddressCellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    OMOriginalAddress *address = self.items[indexPath.row];
    if (![address.id isEqualToString:self.address.id]) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(didSelectItem:AtIndex:)]) {
            [self.delegate didSelectItem:self.items[indexPath.row] AtIndex:indexPath.row];
        }
        KTSystemStorageSingleton.originalAddress = address;
    }
    [self dismiss];
}
@end
